package fr.umlv.escapeir.structure;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;

import fr.umlv.escapeir.painters.WorldPainter;
import fr.umlv.escapeir.painters.WorldGraphics2D;

public class Ship1 implements Structure {
	
	private final BodyDef bdef;
	private Body body;
	private final List<FixtureDef> fdefinitions;
	private final CircleShape cshape;
	private final PolygonShape pshape;
	private WorldPainter structPainter;
	
	public Ship1 (float x, float y, float size) {
		bdef = new BodyDef();
		bdef.type = BodyType.DYNAMIC;
		bdef.position.set(x, y);
		
		pshape = new PolygonShape();
		Vec2 pshapeVec[] = new Vec2[8];
		float onethird = size/3;
		float onesixth = size/6;
		float onesecond = size/2;
		pshapeVec[0] = new Vec2(-onesixth, 0);
		pshapeVec[1] = new Vec2(-onethird, onethird);
		pshapeVec[2] = new Vec2(-onesecond, -onesixth);
		pshapeVec[3] = new Vec2(-onethird, -onethird);
		
		pshapeVec[4] = new Vec2(onethird, -onethird);
		pshapeVec[5] = new Vec2(onesecond, -onesixth);
		pshapeVec[6] = new Vec2(onethird, onethird);
		pshapeVec[7] = new Vec2(onesixth, 0);
		pshape.set(pshapeVec, pshapeVec.length);
		
		cshape = new CircleShape();
		cshape.m_radius = onethird;
		cshape.m_p.set(0,- onethird);
		
		FixtureDef fdefpoly = new FixtureDef();
		fdefpoly.restitution = 0;
		fdefpoly.density = 10;
		fdefpoly.shape = pshape;
		
		FixtureDef fdefcircle = new FixtureDef();
		fdefcircle.restitution = 0;
		fdefcircle.density = 5;
		fdefcircle.shape = cshape;
		
		fdefinitions = new ArrayList<>();
		fdefinitions.add(fdefpoly);
		fdefinitions.add(fdefcircle);
		
		structPainter = new WorldPainter() {
			public void render(WorldGraphics2D painter) {
				painter.save();
				
				System.out.println(getPosition());
				painter.translateFromWorld(getPosition());
				painter.rotate(getAngle());
				painter.setColor(Color.WHITE);
				painter.fillShape(pshape);
				painter.setColor(Color.RED);
				painter.fillShape(cshape);
				painter.restore();
			}
		};
	}

	private Vec2 getPosition() {
		return body.getPosition();
	}

	private float getAngle() {
		return body.getAngle();
	}

	@Override
	public void finalize(Body body, BodyDef bdef) {
		this.body = body;
		this.body.m_userData = this;
		for (FixtureDef f : fdefinitions)
			body.createFixture(f);
	}

	@Override
	public List<BodyDef> getBodyDefinitions() {
		return Collections.singletonList(bdef);
	}

	@Override
	public WorldPainter getPainter() {
		return structPainter;
	}

	@Override
	public void setPainter(WorldPainter painter) {
		structPainter = painter;
	}
}
